package cn.xuqiudong.duoduo.console.resource.service;

import cn.xuqiudong.common.base.service.BaseService;
import cn.xuqiudong.duoduo.console.resource.mapper.ResourceMapper;
import cn.xuqiudong.duoduo.console.resource.model.VicResource;
import cn.xuqiudong.duoduo.util.CommonIoUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 *功能: :资源数据 Service
 * @author Vic.xu
 * @since  2024-04-08 14:46
 */
@Service
public class ResourceService extends BaseService<ResourceMapper, VicResource>{

    @Override
    protected boolean hasAttachment() {
        return false;
    }


    public void previewResource(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (id == null) {
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        VicResource resource = findById(id);
        if (resource == null) {
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        switch (resource.getOrigin()) {
            case local:
                CommonIoUtils.download(new File(resource.getFilePath()), response, null, resource.getFileName());
                break;
            case network:
                response.sendRedirect(resource.getFilePath());
                break;
            case attachment:
                // TODO
                break;
            default:
                sendError(response);
        }
    }




    private void sendError(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.NOT_FOUND.value());
    }



}
